// pages/main/create/create.js
Page({
  data: {
    createApps: [],
    loading: true,
    userInfo: {}
  },

  onLoad() {
    this.loadUserInfo();
    this.loadUserApplications();
  },

  onShow() {
    // 每次显示页面时重新加载，确保权限变更后能及时更新
    this.loadUserApplications();
  },

  // 加载用户信息
  loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync('user_info');
      if (userInfo) {
        this.setData({ userInfo });
      }
    } catch (e) {
      console.error('获取用户信息失败:', e);
    }
  },

  // 加载用户有权限的应用
  loadUserApplications() {
    const username = wx.getStorageSync('username');
    if (!username) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      this.setData({ loading: false });
      return;
    }

    this.setData({ loading: true });

    wx.request({
      url: `${getApp().globalData.serverUrl}/GetUserApplications/`,
      method: 'POST',
      data: {
        username: username
      },
      success: (res) => {
        if (res.data.status) {
          const applications = res.data.applications || [];
          
          // 过滤出新建类型的应用，并添加默认的新建功能映射
          const createApps = this.mapToCreateApps(applications);
          
          this.setData({
            createApps: createApps,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取应用列表失败',
            icon: 'none'
          });
          this.setData({ 
            createApps: [],
            loading: false 
          });
        }
      },
      fail: (err) => {
        console.error('获取应用列表失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ 
          createApps: [],
          loading: false 
        });
      }
    });
  },

  // 将应用映射为新建功能
  mapToCreateApps(applications) {
    // 定义应用名称到新建功能的映射关系
    const createMapping = {
      '估价项目': {
        name: '估价项目',
        icon: 'icon-project',
        color: '#4caf50',
        url: '/pages/main/common-apply/common-apply'
      },
      '资产项目': {
        name: '资产项目',
        icon: 'icon-asset',
        color: '#2196f3',
        url: '/pages/main/common-apply/common-apply'
      },
      '规划勘测': {
        name: '勘测项目',
        icon: 'icon-survey',
        color: '#2196f3',
        url: '/pages/main/common-apply/common-apply'
      },
      '经纪业务': {
        name: '经纪业务',
        icon: 'icon-brokerage',
        color: '#2196f3',
        url: '/pages/main/common-apply/common-apply'
      },
      '经纪资管': {
        name: '资管项目',
        icon: 'icon-asset-management',
        color: '#f44336',
        url: '/pages/main/common-apply/common-apply'
      },
      '征收业务': {
        name: '征收项目',
        icon: 'icon-collection',
        color: '#ff9800',
        url: '/pages/main/common-apply/common-apply'
      },
      '行政人事': {
        name: '人事申请',
        icon: 'icon-hr',
        color: '#ffeb3b',
        url: '/pages/main/common-apply/common-apply'
      },
      '财务管理': {
        name: '财务申请',
        icon: 'icon-finance',
        color: '#4caf50',
        url: '/pages/main/common-apply/common-apply'
      },
      '客户管理': {
        name: '新建客户',
        icon: 'icon-customer',
        color: '#00bcd4',
        url: '/pages/main/common-apply/common-apply'
      },
      '招投标管理': {
        name: '新建招标',
        icon: 'icon-bidding',
        color: '#9c27b0',
        url: '/pages/main/common-apply/common-apply'
      },
      '合同管理': {
        name: '新建合同',
        icon: 'icon-contract',
        color: '#3f51b5',
        url: '/pages/main/common-apply/common-apply'
      }
    };

    const createApps = [];
    let idCounter = 1;

    // 遍历用户有权限的应用，映射到新建功能
    applications.forEach(app => {
      const mapping = createMapping[app.name];
      if (mapping) {
        if (Array.isArray(mapping)) {
          // 如果是数组，说明一个应用对应多个新建功能
          mapping.forEach(createFunc => {
            createApps.push({
              id: idCounter++,
              appId: app.id,
              appName: app.name,
              ...createFunc
            });
          });
        } else {
          // 单个新建功能
          createApps.push({
            id: idCounter++,
            appId: app.id,
            appName: app.name,
            ...mapping
          });
        }
      } 
      // else {
      //   // 对于没有特定映射的应用，添加通用的新建入口
      //   createApps.push({
      //     id: idCounter++,
      //     appId: app.id,
      //     appName: app.name,
      //     name: `新建${app.name}`,
      //     icon: app.icon,
      //     color: app.color,
      //     url: '/pages/create/addproject/addproject'
      //   });
      // }
    });

    // 添加新建商机（独立入口）
    createApps.push({
      id: idCounter++,
      appId: 'chance',
      appName: '商机',
      name: '新建商机',
      icon: 'icon-chance', 
      color: '#ff5722',
      url: '/pages/main/common-apply/common-apply'
    });

    // 按名称排序
    return createApps.sort((a, b) => a.name.localeCompare(b.name));
  },

  // 点击新建功能
  onAppTap(e) {
    const app = e.currentTarget.dataset.app;
    console.log('点击新建功能:', app);
    
    if (app.url) {
      let targetUrl = app.url;
      
      // 如果是通用的addproject页面，需要传递应用ID参数
      if (app.url === '/pages/main/common-apply/common-apply') {
        targetUrl = `${app.url}?appId=${app.appId}&appName=${encodeURIComponent(app.appName)}`;
      }
      
      wx.navigateTo({
        url: targetUrl,
        fail: () => {
          wx.showToast({
            title: '功能开发中',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '功能开发中',
        icon: 'none'
      });
    }
  },

  // 刷新数据
  onRefresh() {
    this.loadUserApplications();
  }
});
